package com.tang.gulimall.product.web;

import com.tang.gulimall.product.common.RedisCache;
import com.tang.gulimall.product.entity.CategoryEntity;
import com.tang.gulimall.product.service.CategoryService;

import com.tang.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private RedisCache redisCache;


    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        //TODO 1、查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        // 视图解析器进行拼串：
        // classpath:/templates/ +返回值+  .html
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        RLock lock = redisson.getLock("my-lock");
        //加锁
        //阻塞式等待
        //redisson的优势
        //1.锁的自动续期 保证业务代码执行完
        //2.锁的自动释放 如果不手动释放 当业务代码执行完之后 不会给锁续期，有效期到了会删除redis的key保证释放锁
        lock.lock();
        try {
            System.out.println("执行业务逻辑!" + Thread.currentThread().getId());
            Thread.sleep(15000);
        } catch (Exception e) {

        } finally {
            //解锁
            System.out.println("解锁!" + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }


    /**
     * 读写锁案例
     * 读锁是一个共享锁 写锁是一个排他锁 (读+读可以同时进行,而读+写,写+读,写+写都是互斥的) 保证了读的都是最新数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/write")
    public String write() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("write-lock");
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            String s = UUID.randomUUID().toString();
            Thread.sleep(3000);
            redisCache.setCacheObject("write",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return "write";
    }


    @ResponseBody
    @RequestMapping("/read")
    public String read() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("write-lock");
        RLock rLock = readWriteLock.readLock();
        String result = "";
        rLock.lock();
        try {
            System.out.println("读业务....");
            Thread.sleep(8000);
            result = redisCache.getCacheObject("write");
        } catch (Exception e){

        }finally {
            rLock.unlock();
        }
        return result;
    }

    /**
     * 信号量演示
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @RequestMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //获取一个信号量 对于的值减一 占一个车位
        //如果没车位 阻塞等待
        // park.acquire();
        boolean b = park.tryAcquire();
        if (b) {
            //表示有车位
            //执行业务逻辑
        } else {
            //表示没有车位
            //返回相关数据
        }
        return "park";
    }


    /**
     * 信号量演示
     * @return
     */
    @ResponseBody
    @RequestMapping("/go")
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        //释放信号量 对应的值加一 释放一个车位
        park.release();
        return "go";
    }

    /**
     * 闭锁演示
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @RequestMapping("/lockdoor")
    public String lockdoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        //等待其他线程完成
        door.await();
        return "放假了";
    }


    /**
     * 闭锁演示
     * @param id
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @RequestMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Integer id) throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        //计数器减一
        door.countDown();
        return id+"班放假了";
    }
}
